package net.sunofbeach.blog.controller.portal;

import com.wf.captcha.SpecCaptcha;
import com.wf.captcha.base.Captcha;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import net.sunofbeach.blog.pojo.Comment;
import net.sunofbeach.blog.pojo.User;
import net.sunofbeach.blog.response.Result;
import net.sunofbeach.blog.response.ResultEnum;
import net.sunofbeach.blog.service.CommentService;
import net.sunofbeach.blog.service.UserService;
import net.sunofbeach.blog.utils.Constants;
import net.sunofbeach.blog.utils.CookieUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.util.concurrent.TimeUnit;

/**
 * @author bing_  @create 2021/11/24-11:15
 */
@Slf4j
@Api(tags = "测试接口：新增评论、图灵验证码.....")
@RestController
@RequestMapping("/test")
public class TestController {

    @Resource
    private RedisTemplate redisTemplate;

    @GetMapping("/hello")
    public Result helloWorld() {
        // 获取 redis 中的验证码
        String captchaContent = (String) redisTemplate.opsForValue().get(Constants.User.KEY_CAPTCHA_CONTENT + "123456");
        log.info("captchaContent ==> " + captchaContent);
        return Result.ok(captchaContent);
    }

    @PostMapping("/login")
    public Result testLogin(@RequestBody User user) {
        log.info("username ==> " + user.getUsername());
        log.info("password ==> " + user.getPassword());
        Result logonSuccess = new Result(ResultEnum.LOGIN_FAIL);
        return logonSuccess;
    }


    /**
     * 图片验证码
     *
     * @throws Exception 文档： https://codechina.csdn.net/mirrors/whvcse/easycaptcha
     *                   可以设置字符类型、字体
     *                   http://localhost:2021/test/captcha
     */
    @RequestMapping("/captcha")
    public void captcha(HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 设置请求头为输出图片类型
        response.setContentType("image/gif");
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);

        // 三个参数分别为宽、高、位数
        SpecCaptcha specCaptcha = new SpecCaptcha(130, 48, 5);
        // 设置字体（有默认字体，可以不用设置）
        specCaptcha.setFont(Captcha.FONT_1);
        // 设置类型，纯数字、纯字母、字母数字混合
        specCaptcha.setCharType(Captcha.TYPE_ONLY_NUMBER);
        // 更多验证码类型
        //TYPE_DEFAULT  数字和字母混合
        //TYPE_ONLY_NUMBER  纯数字
        //TYPE_ONLY_CHAR  纯字母
        //TYPE_ONLY_UPPER  纯大写字母
        //TYPE_ONLY_LOWER  纯小写字母
        //TYPE_NUM_AND_UPPER  数字和大写字母

        // 获取验证码内容
        String content = specCaptcha.text().toLowerCase();
        log.info("captcha content ==> " + content);

        //// 将验证码存入 redis, 10分钟内有效
        redisTemplate.opsForValue().set(Constants.User.KEY_CAPTCHA_CONTENT + "123456", content, 10, TimeUnit.MINUTES);

        // 验证码存入session
        request.getSession().setAttribute("captcha", specCaptcha.text().toLowerCase());
        // 输出图片流
        specCaptcha.out(response.getOutputStream());
    }


    @Resource
    private CommentService commentService;

    @Resource
    private UserService userService;

    /**
     * 新增评论
     *
     * @param comment
     * @param request
     * @return
     */
    @Transactional(rollbackFor = Exception.class, isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED)
    @ApiOperation("测试使用token新增评论")
    @PostMapping("/comment")
    public Result testComment(@RequestBody Comment comment, HttpServletRequest request, HttpServletResponse response) {
        //String content = comment.getContent();
        //log.info("comment content ==> " + content);
        // 还得知道是谁的评论，对这个评论，份进行确定
        // 使用工具类获取 cookie
        String tokenKey = CookieUtils.getCookie(request, Constants.User.COOKIE_TOKEN_KEY);
        if (tokenKey == null) {
            return Result.fail().message("账号未登录");
        }
        User user = userService.checkSobUser();
        if (user == null) {
            return Result.fail().message("账号未登录");
        }
        comment.setUserId(user.getId());
        comment.setUserAvatar(user.getAvatar());
        comment.setUsername(user.getUsername());
        comment.setCreateTime(LocalDateTime.now());
        comment.setUpdateTime(LocalDateTime.now());
        comment.setState("1");

        commentService.save(comment);
        return Result.ok().message("评论成功");

    }


}




















